/*
 * Copyright 2010 Pierre-Yves Ricau
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.excilys.capiq.client.view;

import com.excilys.capiq.client.LoginInfo;
import com.excilys.capiq.client.service.LoginService;
import com.excilys.capiq.client.service.LoginServiceAsync;
import com.excilys.capiq.client.service.QuestionServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Widget;

public class GlobalContainerWidget extends Composite {

    interface GlobalContainerBinder extends UiBinder<Widget, GlobalContainerWidget> {}

    private static GlobalContainerBinder uiBinder           = GWT.create(GlobalContainerBinder.class);

    @UiField
    ScrollPanel                          answer;

    @UiField
    ScrollPanel                          add;

    @UiField
    ScrollPanel                          scores;

    @UiField
    Anchor                               signInOut;

    private boolean                      excellenceSwitched = false;

    private DialogBox                    humorDialog;

    @UiField
    Anchor                               excellence;

    @UiField
    TabLayoutPanel                       tabPanel;

    private final QuestionServiceAsync   questionService;

    public GlobalContainerWidget(QuestionServiceAsync questionService) {

        initWidget(uiBinder.createAndBindUi(this));

        this.questionService = questionService;

        LoginServiceAsync loginService = GWT.create(LoginService.class);
        loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
            public void onFailure(Throwable error) {
                Window.alert("Erreur: " + error.getMessage());
            }

            public void onSuccess(LoginInfo loginInfo) {
                if (loginInfo.isLoggedIn()) {
                    loadSignedIn(loginInfo);
                } else {
                    loadLogin(loginInfo);
                }
            }
        });

        scores.setWidget(new UserScoresWidget(questionService));

        createHumorDialog();

        tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
            public void onSelection(SelectionEvent<Integer> event) {
                History.newItem("page" + event.getSelectedItem());
            }
        });

        History.addValueChangeHandler(new ValueChangeHandler<String>() {
            public void onValueChange(ValueChangeEvent<String> event) {
                String historyToken = event.getValue();

                // Parse the history token
                try {
                    if (historyToken.substring(0, 4).equals("page")) {
                        String tabIndexToken = historyToken.substring(4, 5);
                        int tabIndex = Integer.parseInt(tabIndexToken);
                        // Select the specified tab panel
                        tabPanel.selectTab(tabIndex);
                    } else {
                        tabPanel.selectTab(0);
                    }
                } catch (IndexOutOfBoundsException e) {
                    tabPanel.selectTab(0);
                }
            }
        });

        History.fireCurrentHistoryState();

    }

    private void loadSignedIn(LoginInfo loginInfo) {
        signInOut.setText(loginInfo.getNickname() + " (Se déconnecter)");
        signInOut.setHref(loginInfo.getLogoutUrl());
        add.setWidget(new AddQuestionWidget(questionService));
        answer.setWidget(new AnswerQuestionWidget(questionService));

    }

    private void loadLogin(LoginInfo loginInfo) {
        signInOut.setText("Se connecter sur excilys.com");
        signInOut.setHref(loginInfo.getLoginUrl());
        answer.setWidget(new LoginWidget(loginInfo.getLoginUrl()));
        add.setWidget(new LoginWidget(loginInfo.getLoginUrl()));
    }

    @UiHandler("excellence")
    public void handleExcellence(ClickEvent click) {
        if (excellenceSwitched) {
            excellenceSwitched = false;
            excellence.setText("Quand je pense Excellence...");
        } else {
            excellenceSwitched = true;

            showHumorDialog();

        }
    }

    private void createHumorDialog() {
        humorDialog = new DialogBox();

        FlowPanel dialogPanel = new FlowPanel();

        humorDialog.setText("Avez-vous un sens de l'humour et une capacité à prendre les choses au 42e degré ?");
        Button dialogYes = new Button("Oui, je suis un rigolo !");
        Button dialogNo = new Button("Non, j'ai un balai dans le cou.");

        dialogYes.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                humorDialog.hide();
                excellence.setText("... je pisse Exc**** !");
            }
        });

        dialogNo.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                humorDialog.hide();
                excellence.setText("... comment est votre blanquette ?");
            }
        });

        dialogPanel.add(dialogYes);
        dialogPanel.add(dialogNo);
        humorDialog.setWidget(dialogPanel);

        humorDialog.setGlassEnabled(true);

    }

    private void showHumorDialog() {
        humorDialog.center();
    }
}
